import socket
import network

from tem import getdht
from machine import Pin, PWM
import time
import network
import time
from wifi import wifi

p25 = Pin(25, Pin.OUT)
p26 = Pin(26, Pin.OUT)
global wifi_pass
global wifi_user
isauto=True
low=50
center=70
shun=1
wenduAndshidu=[0,0]
wenORshi=1#初始湿度
# 定义GPIO引脚
# 控制1个电机
def auto(shidu):#温度或者湿度
    #if(shidu<=low):
        #dianji_begain(500)
    #elif(shidu>low and shidu<=center):
        #dianji_begain(800)
    #elif(shidu > center):
        #dianji_begain(1023)
    print("center is"+str(center)+"low is"+str(low))
def dianji_off():
    # 2个电机停止转动
    p25.off()
    p26.off()

def dianji_begain(num):

    ENA = PWM(Pin(33))
    ENA.duty(num)
    # 2个电机朝1个方向转2秒
    p25.value(1 - shun)
    p26.value(shun)

    # 2个电机朝另外1个方向转2秒
    #p25.value(0)
    #p26.value(1)
    #time.sleep(2)

    # 2个电机停止转动
   # p25.value(0)
   # p26.value(0)
    #time.sleep(1)
def control_blue(command,para,yuan):
    print(command+"命令")
    print(para+"参数")
    if command=="kaifengshan":
        if para.startswith("on"):
            dianji_begain(800)
            print("风扇已打开")
        elif para.startswith("off"):
            dianji_off()
            print("风扇已关闭")
    elif command=="tiaojiefengsu":
        if para.startswith("2"):
            dianji_begain(600)
            print("2档")
        elif para.startswith("3"):
            dianji_begain(800)
            print("3档")
        elif para.startswith("4"):
            dianji_begain(999)
            print("4档")
    elif command=="cou":
        print("wifi 名")
        global wifi_user
        wifi_user=para
    elif command=="cop":
        print("wifi 密码")
        global wifi_pass
        global wifi_user
        wifi_pass=para
        wifi(wifi_user,wifi_pass)

from machine import Pin
from machine import Timer
from time import sleep_ms
import bluetooth
import main
# 定义全局变量
BLE_MSG = ""

class ESP32_BLE():
    def __init__(self, name):

        self.led = Pin(2, Pin.OUT)
        self.timer1 = Timer(0)
        self.name = name

        self.ble = bluetooth.BLE()
        self.ble.active(True)
        self.ble.config(gap_name=name)
        self.disconnected()
        self.ble.irq(self.ble_irq)
        self.register()
        self.advertiser()

    def connected(self):
        self.led.value(1)
        self.timer1.deinit()

    def disconnected(self):
        self.timer1.init(period=1000, mode=Timer.PERIODIC, callback=lambda t: self.led.value(not self.led.value()))
        #self.led.value(0)

    def ble_irq(self, event, data):
        global BLE_MSG
        #_IRQ_CENTRAL_CONNECT 蓝牙终端链接了此设备
        if event == 1:
            self.connected()
        #_IRQ_CENTRAL_DISCONNECT 蓝牙终端断开此设备
        elif event == 2:
            self.advertiser()
            self.disconnected()
        #_IRQ_GATTS_WRITE 蓝牙终端向ESP32发送数据，接收数据处理
        elif event == 3:
            buffer = self.ble.gatts_read(self.rx)
            BLE_MSG = buffer.decode('UTF-8').strip().replace("\"","").replace("\0","")
            conmand=BLE_MSG.split("-")[0]
            para=BLE_MSG.split("-")[1]
            control_blue(conmand,para,BLE_MSG)
            #print(conmand)
            print("接收到其他蓝牙终端发来的数据:",BLE_MSG)

    def register(self):
        service_uuid = '6E400001-B5A3-F393-E0A9-E50E24DCCA9E'
        reader_uuid = '6E400002-B5A3-F393-E0A9-E50E24DCCA9E'
        sender_uuid = '6E400003-B5A3-F393-E0A9-E50E24DCCA9E'
        services = (
            (
                bluetooth.UUID(service_uuid),
                (
                    (bluetooth.UUID(sender_uuid), bluetooth.FLAG_NOTIFY),
                    (bluetooth.UUID(reader_uuid), bluetooth.FLAG_WRITE),
                )
            ),
        )
        ((self.tx, self.rx,), ) = self.ble.gatts_register_services(services)

    def send(self, data):
        self.ble.gatts_notify(0, self.tx, data + '\n')

    def advertiser(self):
        name = bytes(self.name, 'UTF-8')
        adv_data = bytearray('\x02\x01\x02', 'UTF-8') + bytearray((len(name) + 1, 0x09), 'UTF-8') + name
        self.ble.gap_advertise(100, adv_data)
        print(adv_data)
        print("\r\n")

def main1(BLE_NAME):
    global BLE_MSG
    #调用BLE 设置ESP32被发现的蓝牙名称 名称为主程序传参传入
    ble = ESP32_BLE(BLE_NAME)
    #蓝牙指示灯(板载蓝色LED)，当ESP32设备未被连接，则周期闪烁；若被连接，则常亮
    led = Pin(2, Pin.OUT)
main1("wlt's ESP32")#启动蓝牙服务

print("wlt'sESP32 ready")


# 绑定服务器IP和端口
dianji_off()



# 发送响应消息给客户端
# response = f'已收到您的消息：{data.decode()}'
# sock.sendto(response.encode(), addr)

